<template>
  <div>
    <div
      id="trace-main"
      style="position: absolute; width: 100%; height: 100vh"
    ></div>
  </div>
</template>

<script>
import { Map, View, Feature } from "ol";
const TileLayer = ol.layer.Tile;
const VectorLayer = ol.layer.Vector;
const { OSM, Vector: VectorSource, XYZ } = ol.source;
const { Point, LineString } = ol.geom;
const { Circle: CircleStyle, Fill, Icon, Stroke, Style } = ol.style;
const { getVectorContext } = ol.render;
const { fromLonLat, toLonLat } = ol.proj;
const context = {
  map: null,
};

export default {
  props: {
    trace: Array,
  },
  methods: {
    init() {
      context.map = new Map({
        target: "main",
        layers: [
          new TileLayer({
            source: new OSM(),
          }),
        ],
        view: new View({
          center: fromLonLat([114.3, 30.5]),
          zoom: 10,
        }),
      });
      this.initTrace(this.trace);
    },

    initTrace(data) {
      data.forEach((v) => {
        // console.log(v)
        context.map.addLayer(this.createOneTrace(v.traces));
      });
    },

    createOneTrace(trace) {

      let points = [];
      console.log(trace);
      trace.forEach((v) => {
        let marker = new Feature({
          type: "icon",
          geometry: new Point(fromLonLat([v.positions.lon, v.positions.lats])),
        });
        points.push(marker);
      });
      let coors = trace.map((v) => {
        return fromLonLat([v.positions.lon, v.positions.lats]);
      });
      let lines = [];
      for (let i = 0; i < coors.length - 1; i++) {
        let line = new Feature({
          geometry: new LineString([coors[i], coors[i + 1]]),
          type: "route",
        });
        lines.push(line);
      }
      let features = points.concat(lines);

      let vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: features,
        }),
        style: function (feature) {
          // hide geoMarker if animation is active
          //   if (animating && feature.get("type") === "geoMarker") {
          //     return null;
          //   }
          let styles = {
            route: new Style({
              stroke: new Stroke({
                width: 6,
                color: [21, 21, 21, 0.8],
              }),
            }),
            icon: new Style({
              image: new Icon({
                anchor: [0.5, 1],
                scale: 0.2,
                src: positionImage,
                color: [21, 21, 21, 0.8],
              }),
            }),
            geoMarker: new Style({
              image: new CircleStyle({
                radius: 7,
                fill: new Fill({ color: "black" }),
                stroke: new Stroke({
                  color: "white",
                  width: 2,
                }),
              }),
            }),
          };
          return styles[feature.get("type")];
        },
      });

      return vectorLayer;
    },
  },
};
</script>

<style>
</style>